<template>
  <el-main>
    <!-- 搜索栏 -->
    <el-form size="mini" :model="roleForm" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="角色名称" size="normal">
            <el-input
              v-model="searchName"
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="sendSearch">搜索</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="addRole"
            >新增</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格区域 -->

    <el-table
      style="width: 100%"
      :height="tableHeight"
      :data="tableData"
    >
      <el-table-column label="角色名称" prop="name" align="center">
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center">
      </el-table-column>
      <el-table-column align="right">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="success"
            @click="handleAssgin(scope.$index, scope.row)"
            >权限设置</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑角色弹出框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="roleForm"
        ref="editform"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="roleForm.detail"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="角色授权"
      :visible.sync="assignVisible"
      width="50%"
      class="self_dialog"
    >
      <tree
        :setting="setting"
        :nodes="nodes"
        @onCreated="handleCreated"
      />
      <span slot="footer">
        <el-button @click="assignCancle">取消</el-button>
        <el-button type="primary" @click="assignConfirm">确定</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totle"
    >
    </el-pagination>
  </el-main>
</template>

<script>
import tree from "vue-giant-tree";
import api from "../../../utils/axios/api";
export default {
  components: {
    tree,
  },
  name: "RoleList",
  data() {
    return {
      searchName:"",
      // 编辑模式  0 新增 1 编辑
      editTag:0,
      // 弹窗标题
      dialogTitle:"新增角色",
      // 设置授权弹窗的可见属性
      assignVisible: false,
      // 设置表格的高度
      tableHeight: window.innerHeight - 350,
      // 是否显示对话框
      dialogVisible: false,
      //   当前页码
      currentPage: 1,
      // 当前页数量
      pageSize:5,
      // 数据总数量
      totle:0,
      //   表单模型
      roleForm: {
        id:0,
        // 角色编码
        code:"",
        // 角色名称
        name: "",
        // 角色备注
        detail:""

      },
      //   表单验证规则
      rules: {
        name: [
          {
            required: true,
            trigger: "change",
            message: "请输入角色名称",
          },
        ],
        code: [
          {
            required: true,
            trigger: "change",
            message: "请输入角色编码",
          },
        ],

      },
      ztreeObj: null,
      //ztree配置，参照ztree官网的配置
      setting: {
        check: {
          //树是否带复选框或者单选框
          enable: true,
        },
        data: {
          simpleData: {
            //是否使用简单数据模式
            enable: true,
            //树节点id，一般是后台数据库主键
            idKey: "id",
            //父级id
            pIdKey: "pid",
            rootPId: "0",
          },
        },
        //ztree回调函数
        callback: {
          //树选择事件
          onCheck: this.ztreeOnCheck,
        },
      },
      nodes: [],

      //   表格数据
      tableData: [

      ],
      currentRoleId:"",
    };
  },
  methods: {
    // 搜索角色
    sendSearch(){
      this.roleForm.name=this.searchName;
      this.getRoleList();
    },
    // 新增角色对话框
    addRole(){
      this.dialogVisible=true;
      this.editTag=0;
      this.resetForm("editform");
    },
    // 编辑角色
    handleEdit(index, row) {
      this.editTag=1;
      this.dialogVisible = true;
      this.getRoleById(row.id);
    },
    // 删除角色
    async handleDelete(index, row) {
      let _this=this;
      _this.$confirm("确定删除吗 ?","系统提示",{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async ()=>{
        let param={
          id:row.id
        }
        let {data:res}=await api.deleteRoleById(param);
        if(res.code==0){
          _this.$message({
            message:res.msg,
            type:"success"
          })
          this.getRoleList();
        }
      })


    },
    // 创建目录树时触发
    handleCreated(ztreeObj) {
      this.ztreeObj = ztreeObj;
      // onCreated 中操作ztreeObj对象展开第一个节点
      // ztreeObj.expandAll(true);
    },
    async assignConfirm() {
      let selectNodes=this.ztreeObj.getCheckedNodes();
      let updatenodes=[];
      // 遍历所有选中的节点提取出Id值
      selectNodes.forEach(function (p) {
        updatenodes.push(p.id);
      })
      // 首先删除以前改角色的全部权限信息
      let params={
        roleId:this.currentRoleId,
        permissionIds:updatenodes
      }
      let {data:res}=await api.updateRolePermission(params);
      if(res.code==0){
        this.$message({
          message:"编辑成功",
          type:"success"
        })
        this.assignVisible=false;
      }

      // 重新保存角色的全部角色信息
    },
    assignCancle() {
      this.assignVisible=false;
    },
   // 每页数量变化时重新加载数据
    handleSizeChange(val) {
      this.pageSize=val;
      this.getRoleList();
    },
    // 当前页码变化时重新加载数据
    handleCurrentChange(val) {
      this.currentPage=val;
      this.getRoleList();
    },
    handleClose() {},
    handleAssgin(index, row) {
      this.assignVisible = true;
      this.currentRoleId=row.id;
      this.getTreeNodes(row.id);
    },
    // 对话框确认方法
    confirm() {
      let _this=this;
      let res=null;
      _this.$refs.editform.validate(async (valid) => {
        if (valid) {
          let params={
            id:_this.roleForm.id,
            code:_this.roleForm.code,
            name:_this.roleForm.name,
            remark:_this.roleForm.detail
          }
          if(_this.editTag==0){
            res=await api.addNewRole(params);
          }
          if(_this.editTag==1){
            res=await api.editRole(params);
          }
          let data=res.data;
          if(data.code==0){
            _this.$message({
              message:data.msg,
              type:"success"
            })
            _this.dialogVisible=false;
            _this.getRoleList();
          }

        }
      });
    },
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 加载当前权限节点
    async getTreeNodes(roleId){
      let _this=this;
      let param={
          id:roleId
      };
      let {data:res}=await api.getTreeNodeList(param);
      if(res.code==0){
        _this.nodes=res.data;
      }

    },

    // 查询角色列表
    async getRoleList(){
      let _this=this;
      _this.resetForm("editform");
      let params={
        pageSize:_this.pageSize,
        title:_this.roleForm.name,
        currentPage:_this.currentPage
      }
      let{data:res}=await api.getRoleList(params);
      if(res.code==0){
        _this.tableData=res.data.records;
        _this.currentPage = res.data.current;
        _this.pageSize = res.data.size;
        _this.totle = res.data.total;
      }
    },
    async getRoleById(id){
      this.resetForm("editform");
      let param={
        id:id
      };
      let{data:res}=await api.getRoleById(param);
      if(res.code==0){
        this.roleForm.name=res.data.name;
        this.roleForm.code=res.data.code;
        this.roleForm.detail=res.data.remark;
        this.roleForm.id=res.data.id;
      }
    }

  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 350; //后面的50：根据需求空出的高度，自行调整
    });
  },
  created() {
    this.getRoleList();

  }
};
</script>

<style scoped>
.el-main{
  padding-top: 2px !important;
}
.self_dialog {
  display: flex;
  justify-content: center;
  align-items: Center;
  overflow: hidden;
}
.self_dialog /deep/ .el-dialog {
  margin: 0 auto !important;
  height: 90%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding-left: 15px;
}
.self_dialog /deep/ .el-dialog .el-dialog__body {
  padding-top: 5px !important;
  overflow: hidden;
  overflow-y: auto;
  margin-bottom: 40px;
}
.self_dialog /deep/ .el-dialog .el-dialog__footer {
  left: 40%;
  bottom: 0;
  position: absolute;
}
</style>